/**
 * ©2013-2015 Alan L. Rights Reserved.
 */
package org.freedom.railhunter.service;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.freedom.railhunter.util.HttpConnectionManager;
import org.freedom.railhunter.config.PathConfig;
import org.freedom.railhunter.model.AcceptDataType;
import org.freedom.railhunter.model.Station;
import static org.freedom.railhunter.service.BaseService.yyyy_mm_dd_format;
import org.freedom.railhunter.util.StationManager;
import org.freedom.railhunter.util.UnicodeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Alan
 */
public class CookieService extends BaseService {
    
    private static final Logger logger = LoggerFactory.getLogger(CookieService.class);
    
    public static final String JSESSIONID = "JSESSIONID";
    public static final String BIGIP_SERVEROTN = "BIGipServerotn";
    
    public static final String JC_SAVE_FROMDATE = "_jc_save_fromDate";
    public static final String JC_SAVE_FROMSTATION = "_jc_save_fromStation";
    public static final String JC_SAVE_TODATE = "_jc_save_toDate";
    public static final String JC_SAVE_TOSTATION = "_jc_save_toStation";
    public static final String JC_SAVE_WFDC_FLAG = "_jc_save_wfdc_flag";
    
    private static CookieService  cookieService;
    
    private Map<String, String> cookieData = new LinkedHashMap<>();
    
    private CookieService() {
    }
    
    public static CookieService getInstance() {
        if (cookieService == null) {
            cookieService = new CookieService();
        }
        return cookieService;
    }
    
    /**
     * 初始化登录用户Cookie数据
     *
     * @return
     */
    public synchronized Map<String, String> initCookie() {
        // 初次建立顺序
        cookieData.put(JSESSIONID, "");
        cookieData.put(JC_SAVE_FROMSTATION, "");
        cookieData.put(JC_SAVE_TOSTATION, "");
        cookieData.put(JC_SAVE_FROMDATE, "");
        cookieData.put(JC_SAVE_TODATE, "");
        cookieData.put(JC_SAVE_WFDC_FLAG, "");
        cookieData.put(BIGIP_SERVEROTN, "");
        
        try {
            HttpResponse response = HttpConnectionManager.getHttpRequest(PathConfig.INDEX_INIT_PATH,
                    PathConfig.INDEX_INIT_PATH, null, AcceptDataType.HTML, null);
            // 获取消息头的信息
            Header[] headers = response.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equals("Set-Cookie")) {
                    String cookie = headers[i].getValue();
                    String cookieName = cookie.split("=")[0];
                    String cookieValue = cookie.split("=")[1].split(";")[0];
                    cookieData.put(cookieName, cookieValue);
                }
            }
            
            // 构建默认JC部分
            Station fromStation = StationManager.NAME_STATION_MAP.get("上海");
            Station toStation = StationManager.NAME_STATION_MAP.get("衡阳");
            putJcSaveData(cookieData, fromStation, toStation, new Date());
            
            logger.info("初始化获取Cookie：" + cookieData);
        } catch (IOException ex) {
            logger.error("初始化获取Cookie异常", ex);
        }
        return cookieData;
    }
    
    public void putJcSaveData(Map<String, String> cookieData, Station fromStaion, Station toStaion, Date date) {
        cookieData.put(CookieService.JC_SAVE_FROMDATE, yyyy_mm_dd_format.format(date));
        String fromStaionStr = UnicodeConverter.toEncodedUnicode(fromStaion.getName(), true)
                .replaceAll("\\\\", "%") + "%2C" + fromStaion.getTelecode();
        cookieData.put(CookieService.JC_SAVE_FROMSTATION, fromStaionStr);
        cookieData.put(CookieService.JC_SAVE_TODATE, yyyy_mm_dd_format.format(new Date()));
        String toStaionStr = UnicodeConverter.toEncodedUnicode(toStaion.getName(), true)
                .replaceAll("\\\\", "%") + "%2C" + toStaion.getTelecode();
        cookieData.put(CookieService.JC_SAVE_TOSTATION, toStaionStr);
        cookieData.put(CookieService.JC_SAVE_WFDC_FLAG, "dc");
    }

    public Map<String, String> getCookieData() {
        if (cookieData.isEmpty()) {
            initCookie();
        }
        return cookieData;
    }
}
